﻿
/***************************************************************************************
   Date    : January 30, 2006
   Purpose : Implement the ScoreSheetXamlClass
   Maintenance Log : 
   Revision		Date			Description 
   --------		----		------------------------------------------------------
	1.0		 07/02/2008		    Initial Release

****************************************************************************************/

using System;
using System.Xml;
using System.IO;
using System.Web;

namespace Hclt.Msft.Til.CricketScoreboard
{
 /// <summary>
 /// Class for for reading XAML as XML document
 /// </summary>
  
    public class ScoreSheetXaml
    {   
        private XmlDocument xamlDoc;//represent XML document
        private XmlNamespaceManager nsmgr;

       /// <summary>
        /// ScoreSheetXaml constructor takes data from web.config file
       /// </summary>
       /// <param name="currentScene"></param>
        public ScoreSheetXaml(ScreenScene currentScene)
        {
            string filePath = string.Empty;

            //switch block get file path from web.config  based upon scene
            switch (currentScene)
            {
                case ScreenScene.BatsmanOut:
                    filePath = Utility.GetStringFromConfig("OutXamlTemplatePath", string.Empty);
                    break;
                case ScreenScene.BattingSheet:
                    filePath = Utility.GetStringFromConfig("BattingXamlTemplatePath", string.Empty);
                    break;
                 case ScreenScene.BowlingSheet:
                    filePath = Utility.GetStringFromConfig("BowlingXamlTemplatePath", string.Empty);
                    break;
                 case ScreenScene.FourHit:
                    filePath = Utility.GetStringFromConfig("FourHitXamlTemplatePath", string.Empty);
                    break;
                 case ScreenScene.InningsOver:
                    filePath = Utility.GetStringFromConfig("SummaryXamlTemplatePath", string.Empty);
                    break;
                 case ScreenScene.SixHit:
                    filePath = Utility.GetStringFromConfig("SixHitXamlTemplatePath", string.Empty);
                    break;
                default:
                    break;
            }

            // this bloack loads the load xml document
            filePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, filePath);
            //if file path exists this block ensures xml is loaded
            if (File.Exists(filePath))
            {
                xamlDoc = new XmlDocument();
                xamlDoc.LoadXml(File.ReadAllText(filePath));
                nsmgr = new XmlNamespaceManager(xamlDoc.NameTable);
                UpdateImagePath();  
            }            
        }
        //updates image path with folder path
        private void UpdateImagePath()
        {
            XmlNodeList nodeList = xamlDoc.GetElementsByTagName("Image");//nodes with image tag name taken in nodelist
            int nodeCount = nodeList.Count;
            XmlAttribute sourceAttribute;
            string requestUrl;
            for (int i = 0; i < nodeCount; i++)
            {
                sourceAttribute = nodeList[i].Attributes["Source"];
                if (sourceAttribute != null && !string.IsNullOrEmpty(sourceAttribute.Value))
                 {
                      requestUrl = HttpContext.Current.Request.Url.AbsoluteUri;
                      requestUrl = requestUrl.Substring(0, requestUrl.LastIndexOf("/"));
                      sourceAttribute.Value = string.Concat(requestUrl, "/Images/", sourceAttribute.Value);
                 }
            }
        }

          /// <summary>
          ///it updates gradient in scoreboard
          /// </summary>
          /// <param name="pathID">
          /// path component of xaml file
          /// </param>
          /// <param name="isActive">
          /// status of player 
          /// </param>
          /// <param name="isName">
            /// used to set  gradient color staus 
          /// </param>
     
        public void UpdateGradientColor(string pathID, bool isActive, bool isName)
        {
            string colorStartValue;
            string colorEndValue;
            string startColorKey;
            string endColorKey;
            if (isActive)
            {
                startColorKey = isName ? "ActiveNameStartColor" : "ActiveDetailsStartColor";
                endColorKey = isName ? "ActiveNameEndColor" : "ActiveDetailsEndColor";
            }
            else
            {
                startColorKey = isName ? "InActiveNameStartColor" : "InActiveDetailsStartColor";
                endColorKey = isName ? "InActiveNameEndColor" : "InActiveDetailsEndColor";
            }

            //retriving values from configuration file
            colorStartValue = Utility.GetStringFromConfig(startColorKey, string.Empty);
            colorEndValue = Utility.GetStringFromConfig(endColorKey, string.Empty);
          

            XmlNodeList nodeList = xamlDoc.GetElementsByTagName("Path.Fill");
            int nodeCount = nodeList.Count;
            XmlAttribute xNameAttribute;
            XmlAttribute colorAttribute;
            XmlNodeList gradientNodeList;
            for (int i = 0; i < nodeCount; i++)
            {
                xNameAttribute = nodeList[i].ParentNode.Attributes["x:Name"];
                if (xNameAttribute != null && xNameAttribute.Value.Equals(pathID))
                {
                    nsmgr.AddNamespace("x", nodeList[i].NamespaceURI);
                    gradientNodeList = nodeList[i].SelectNodes(@"x:LinearGradientBrush/x:LinearGradientBrush.GradientStops/x:GradientStop", nsmgr);
                    for (int j = 0; j < gradientNodeList.Count; j++)
                    {
                        colorAttribute = gradientNodeList[j].Attributes["Color"];
                        if (colorAttribute != null)
                        {
                            colorAttribute.Value = (j == 0) ? colorStartValue : colorEndValue;
                        }
                    }
                    break;
                }
            }
          
        }

        /// <summary>
        /// replace content of textblock by using X:Name property of textblock
        /// </summary>
        /// <param name="nodeID">
        /// reading a node by attribute x:name
        /// </param>
        /// <param name="value">
        /// used to modify text by attribute value
        /// </param>
        public void UpdateXaml(string nodeID, object value)
        {
            XmlNodeList nodeList = xamlDoc.GetElementsByTagName("TextBlock");
            int nodeCount = nodeList.Count;
            XmlAttribute xNameAttribute;
            XmlAttribute textAttribute;
            string nodeValue = HttpContext.Current.Server.HtmlDecode(Convert.ToString(value));
            for (int i = 0; i < nodeCount; i++)
            {
                xNameAttribute = nodeList[i].Attributes["x:Name"];
                if (xNameAttribute != null && xNameAttribute.Value.Equals(nodeID))
                {
                    textAttribute = nodeList[i].Attributes["Text"];
                    if (textAttribute == null)
                    {
                        textAttribute = xamlDoc.CreateAttribute("Text");
                        textAttribute.Value = nodeValue;
                        nodeList[i].Attributes.Append(textAttribute);
                    }
                    else
                    {
                        textAttribute.Value = nodeValue;
                    }
                    break;
                }
                
            }

        }
        /// <summary>
        /// this function load xml content in page.xaml file
        /// </summary>
        public void WriteXaml()
        {
            string xamlContent = xamlDoc == null ? string.Empty : xamlDoc.OuterXml;
            string outPath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"Page.xaml");
            File.WriteAllText(outPath, xamlContent);
        }

    }

}